package com.ctgu.rabbitmq.rabbitmq.delayQueue.deadLetterDelayQueue;

import com.ctgu.rabbitmq.entity.OrdersEntity;
import com.ctgu.rabbitmq.mapper.OrdersMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @ ClassName DeadLetterDelayQueueConsumer
 * @ Author Alex2
 * @ Date 2025/8/15 15:10
 **/
@Log4j2
@Component
public class DeadLetterDelayQueueConsumer {

    private static final String TAG = "Alex";

    private final OrdersMapper ordersMapper;

    public DeadLetterDelayQueueConsumer(OrdersMapper ordersMapper) {
        this.ordersMapper = ordersMapper;
    }

    // 死信队列消费者
    @RabbitListener(queues = DeadLetterDelayQueueConfig.DLX_DELAY_QUEUE)
    public void closeOrder(Long orderId) {
        OrdersEntity order = ordersMapper.selectById(orderId);
        if (order == null) {
            log.warn("{} : 订单不存在，orderId={}", TAG, orderId);
            return;
        }
        if (!"UNPAID".equals(order.getStatus())) {
            log.info("{} : 订单ID={} 当前状态={}，不执行关闭", TAG, orderId, order.getStatus());
            return;
        }
        order.setStatus("CLOSED");
        ordersMapper.updateById(order);
        log.info("{} : 订单ID={} 已超时未支付，状态更新为 CLOSED", TAG, orderId);
    }
}
